<template>
  <a-modal
    width="30%"
    :visible="allotVisible"
    @cancel="cancelAllotModal"
    @ok="handleAllotLeader"
    title="科目分配组长"
  >
    <div class="allot-modal">
      <div class="allotTitle">分配科目:{{ `${curSubject.kmdm}(${curSubject.kmmc})` }}</div>
      <a-form-item label="评阅组长">
        <a-select
          v-model:value="Data.teacherLeaderId"
          show-search
          allowClear
          placeholder="请选择（可按工号搜索）"
          :filter-option="filterOption"
          :options="Data.teacherOptions"
          :field-names="{ label: 'jsxm', value: 'account' }"
        />
      </a-form-item>
    </div>
  </a-modal>
</template>

<script setup lang="ts">
import { reactive, watch } from 'vue'
import { getTeacherCard } from '/@/api/system-manage/teacher-info'
import { useMessage } from '/@/hooks/web/useMessage'
import { allotLeaderTeacher, saveCancelPyzzAccount } from '/@/api/organization/subjectManage'
const { createMessage } = useMessage()
const props = defineProps({
  curSubject: {
    type: Object,
    default: () => {},
  },
  allotVisible: {
    type: Boolean,
    default: false,
  },
})
const Data = reactive({
  teacherOptions: [],
  teacherLeaderId: undefined,
} as any)

const emit = defineEmits(['update:allotVisible', 'success'])

/**
 * 关闭弹窗
 */
function cancelAllotModal() {
  emit('update:allotVisible', false)
}

function filterOption(input: string, option: any = {}) {
  return option['jsxm']?.indexOf(input) >= 0
}

// 分配组长
const handleAllotLeader = async () => {
  if (props.curSubject.pyzzAccount && Data.teacherLeaderId !== props.curSubject.pyzzAccount) {
    let { code, message } = await saveCancelPyzzAccount({
      account: props.curSubject.pyzzAccount,
    })
    if (code !== 200) {
      createMessage.error(message)
    }
  }
  if (!Data.teacherLeaderId) {
    cancelAllotModal()
    emit('success')
    return
  }
  const { code, message } = await allotLeaderTeacher({
    account: Data.teacherLeaderId,
    manageKmdm: props.curSubject.kmdm,
  })
  if (code === 200) {
    cancelAllotModal()
    emit('success')
    createMessage.success('分配成功')
  } else {
    createMessage.error(message)
  }
}

// 教师列表
const getTeacherOptions = async val => {
  const { data } = await getTeacherCard({
    pageSize: 0,
    account: val,
  })
  data.forEach(element => {
    element.jsxm = `(${element.jsxm})${element.account}`
  })
  Data.teacherOptions = data
}

watch(
  () => props.allotVisible,
  async val => {
    Data.teacherLeaderId = undefined
    !Data.teacherOptions.length && getTeacherOptions('')
    if (val) {
      if (props.curSubject.pyzzAccount) {
        Data.teacherLeaderId = props.curSubject.pyzzAccount
      }
    }
  }
)
</script>

<style lang="less" scoped>
.allot-modal {
  padding: 20px;
  .allotTitle {
    padding-bottom: 20px;
    font-size: 16px;
    font-weight: 700;
  }
}
</style>
